package com.example.myapplication.shortvideo.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.dueeeke.videoplayer.player.IjkVideoView;
import com.example.myapplication.R;
import com.example.myapplication.databinding.FragmentShotVideoBinding;
import com.example.myapplication.shortvideo.activity.VideoCommentActivity;
import com.example.myapplication.shortvideo.adapter.ListVideoAdapter;
import com.example.myapplication.shortvideo.bean.VideoListBean;
import com.example.myapplication.shortvideo.contract.VideoContract;
import com.example.myapplication.shortvideo.player.TikTokController;
import com.example.myapplication.shortvideo.utils.HttpProxyCacheUtil;
import com.example.myapplication.shortvideo.utils.ImageUtil;
import com.example.myapplication.shortvideo.utils.NetWorkUtils;
import com.example.myapplication.shortvideo.utils.tikTok.OnViewPagerListener;
import com.example.myapplication.shortvideo.utils.tikTok.ViewPagerLayoutManager;

import java.util.ArrayList;
import java.util.List;


/**
 * @author: rongfeng
 * @date: 2020/6/16
 * @description
 */
public class VideoFragment extends Fragment implements VideoContract {

    private IjkVideoView mIjkVideoView;
    private TikTokController mTikTokController;
    private ListVideoAdapter videoAdapter;
    private ViewPagerLayoutManager layoutManager;
    private List<Object> mVideoList = new ArrayList<>();
    private int mCurrentPosition;
    private int mCurrentVideoPosition;
    private Context mContext;
    private boolean isClickComment;
    private boolean isClickSuspend;//点击暂停
    FragmentShotVideoBinding binding ;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shot_video, container, false);

        binding = DataBindingUtil.bind(view);

        mContext = getContext();
        for (int i = 0; i < 10; i++) {
            VideoListBean.DataBean.RowsBean rowsBean = new VideoListBean.DataBean.RowsBean();
            rowsBean.setVideoCover("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1592319175661&di=abf293ae8ae5d2fa815100c4eabc50ed&imgtype=0&src=http%3A%2F%2Fcdn.duitang.com%2Fuploads%2Fitem%2F201412%2F27%2F20141227150432_FeS8P.jpeg");
            rowsBean.setVideoAddress("https://image.hualu.yetter.cn/episode/yt/gQzg2uJN1Fg/1584794402034");
            mVideoList.add(rowsBean);
        }
        initView();
        return view;
    }

    private void initView() {
        mIjkVideoView = new IjkVideoView(mContext);
        mIjkVideoView.setLooping(true);
        mTikTokController = new TikTokController(getActivity());
        mIjkVideoView.setVideoController(mTikTokController);
        mIjkVideoView.setPlayOnMobileNetwork(true);
        mIjkVideoView.setScreenScale(IjkVideoView.SCREEN_SCALE_CENTER_CROP);
        mTikTokController.setStartPlayCallback(new TikTokController.StartPlayCallback() {
            @Override
            public void playing() {
                binding.llNoNetwork.getRoot().setVisibility(View.GONE);
            }

            @Override
            public void notNetWork() {
                binding.llNoNetwork.getRoot().setVisibility(View.VISIBLE);
            }

            @Override
            public void playError() {

            }

        });

        videoAdapter = new ListVideoAdapter(mContext, mVideoList, this);
        layoutManager = new ViewPagerLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        binding.discoveryList.setLayoutManager(layoutManager);
        binding.discoveryList.setAdapter(videoAdapter);
        binding.discoveryList.scrollToPosition(mCurrentPosition);

        layoutManager.setOnViewPagerListener(new OnViewPagerListener() {
            @Override
            public void onInitComplete() {
                if (!NetWorkUtils.isNetConnected(mContext)) {
                    binding.llNoNetwork.getRoot().setVisibility(View.VISIBLE);
                    return;
                } else {
                    binding.llNoNetwork.getRoot().setVisibility(View.GONE);
                }
                //自动播放第一条
                startPlay((VideoListBean.DataBean.RowsBean) mVideoList.get(mCurrentVideoPosition));
            }

            @Override
            public void onPageRelease(boolean isNext, int position) {
                if (mCurrentPosition == position) {
                    mIjkVideoView.release();
                }
                mTikTokController.getThumb().setVisibility(View.GONE);
            }

            @Override
            public void onPageSelected(int position, boolean isBottom) {
                mTikTokController.destroyLoading();
                if (mCurrentPosition == position) {
                    return;
                }
                if (!NetWorkUtils.isNetConnected(mContext)) {
                    binding.llNoNetwork.getRoot().setVisibility(View.VISIBLE);
                    return;
                } else {
                    binding.llNoNetwork.getRoot().setVisibility(View.GONE);
                }
                Object obj = mVideoList.get(position);
                if (mVideoList.get(position) instanceof VideoListBean.DataBean.RowsBean) {
                    VideoListBean.DataBean.RowsBean rowsBean = (VideoListBean.DataBean.RowsBean) obj;
//                    rlCloseVoice.setVisibility(View.VISIBLE);
                    mCurrentPosition = position;
                    startPlay(rowsBean);
                    mCurrentVideoPosition = position;
                    if (mVideoList.size() - position < 5) {
//                        pageNum++;
//                        getVideoList();
                    }
                } else {
                    mCurrentPosition = position;
//                    rlCloseVoice.setVisibility(View.GONE);
                }
            }
        });


    }

    private void startPlay(VideoListBean.DataBean.RowsBean info) {
        View itemView =  binding.discoveryList.getChildAt(0);
        FrameLayout frameLayout = itemView.findViewById(R.id.container);

        if (frameLayout != null) {
            mTikTokController.getThumb().setVisibility(View.VISIBLE);
//            ImageUtil.display(TextUtils.resizeImageUrl(info.getVideoCover(), 720), mTikTokController.getThumb(), 0);
            ImageUtil.display(info.getVideoCover(), mTikTokController.getThumb(), 0);

            ViewParent parent = mIjkVideoView.getParent();
            if (parent instanceof FrameLayout) {
                ((FrameLayout) parent).removeView(mIjkVideoView);
            }
            frameLayout.addView(mIjkVideoView);
            String url = info.getVideoAddress();

            String proxyUrl = HttpProxyCacheUtil.getInstance().getProxy().getProxyUrl(url);
            mIjkVideoView.setUrl(proxyUrl);
            mIjkVideoView.setScreenScale(IjkVideoView.SCREEN_SCALE_CENTER_CROP);
            mIjkVideoView.start();
            refreshVolume();
        }
    }


    private void refreshVolume() {
        boolean silent = TikTokController.volTag;
        if (mIjkVideoView != null) {
            if (silent) {
                mIjkVideoView.setVolume(1f, 1f);//开音
            } else {
                mIjkVideoView.setVolume(0f, 0f);//静音
            }
        }
//        imgCloseVoice.setBackgroundResource(silent ? R.mipmap.icon_open_voice : R.mipmap.icon_close_voice);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mVideoList.size() > 0) {
            Object obj = mVideoList.get(mCurrentPosition);
            if (obj instanceof VideoListBean.DataBean.RowsBean) {
                if(!isClickSuspend){
                    refreshVolume();
                    mIjkVideoView.resume();
                    refreshVolume();
                }
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (isClickComment) {
            isClickComment = false;
        } else {
            mIjkVideoView.pause();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mIjkVideoView.release();
        mTikTokController.destroyLoading();
    }


    /**
     * //点击用户头像
     */
    @Override
    public void clickVideoUserHead() {

    }

    /**
     * 点击喜欢
     */
    @Override
    public void clickVideoLike() {

    }

    /**
     * 点击评论
     */
    @Override
    public void clickVideoComment() {
        isClickComment = true;
        mContext.startActivity(new Intent(mContext, VideoCommentActivity.class));
    }

    /**
     * 点击分享
     */
    @Override
    public void clickVideoShare() {

    }

    /**
     * 单击视频
     */
    @Override
    public void videoOnceClick() {
        isClickSuspend = true;
        if (mIjkVideoView.isPlaying()) {
            mIjkVideoView.pause();
            binding.imgPlay.setVisibility(View.VISIBLE);
        } else {
            mIjkVideoView.resume();
            binding.imgPlay.setVisibility(View.GONE);
        }
    }

    /**
     * 双击视频
     */
    @Override
    public void videoDoubleClick() {

    }
}
